package main

import (
	"fmt"
	"sort"
)

func main() {
	//test()
	//test2()
	//test3()
	//test4()
	//test5()
	test6()
}

//map的声明
func test() {
	//map key-value映射
	var m map[string]string
	//创建map之后需要先make，不然报错，map是无序的
	m = make(map[string]string, 5)
	m["n1"] = "v1"
	m["2"] = "2"
	fmt.Println(m)
}

//声明方式3种
func test2() {
	//1
	var m1 map[string]string
	m1 = make(map[string]string, 2)
	m1["v1"] = "v1"
	fmt.Println(m1)
	//2
	var m2 = make(map[int]int)
	m2[1] = 4
	fmt.Println(m2)
	//3
	var m3 map[int]string = map[int]string{
		1: "m3",
	}
	fmt.Println(m3)
}

//学生信息，每个学生有name与sex
func test3() {
	students := make(map[string]map[string]string)
	students["s1"] = make(map[string]string)
	students["s1"]["name"] = "tom"
	students["s1"]["sex"] = "男"

	students["s2"] = make(map[string]string)
	students["s2"]["name"] = "lucy"
	students["s2"]["sex"] = "女"
	fmt.Println(students)
	fmt.Println(students["s1"])
	fmt.Println(students["s2"]["name"])
	//遍历
	for k1, v1 := range students {
		fmt.Println(k1)
		for k2, v2 := range v1 {
			fmt.Printf("\t %v=>%v\n", v2, k2)
		}
	}
}

//map增删改查
func test4() {
	cities := make(map[string]string)
	cities["c1"] = "beijing"
	cities["c2"] = "chicago"
	fmt.Println(cities)
	//增加
	cities["c3"] = "tokyo"
	fmt.Println("add ", cities)
	//查询
	val, hasKey := cities["c2"]
	if hasKey {
		fmt.Println("exist c2 ", val)
	} else {
		fmt.Println("no c2")
	}
	//修改
	cities["c2"] = "Berlin"
	fmt.Println("update ", cities)
	//删除，不存在则不操作
	delete(cities, "c2")
	fmt.Println("del1 ", cities)
	delete(cities, "c6")
	fmt.Println("del2 ", cities)
	//全部删除，1遍历删除，2重新make
	cities = make(map[string]string)
	fmt.Println("del3 ", cities)
}

//map切片
func test5() {
	var monsters []map[string]string
	monsters = make([]map[string]string, 2)
	if monsters[0] == nil {
		monsters[0] = make(map[string]string, 2)
		monsters[0]["name"] = "倾注小妖"
		monsters[0]["age"] = "100"
	}
	newMonster := map[string]string{
		"name": "无名大妖",
		"age":  "201",
	}
	monsters = append(monsters, newMonster)
	fmt.Println(monsters)
}

//对map进行排序
/*
将map的key取出放入切片中
将切片排序
根据切片顺序打印map
*/
func test6() {
	var m1 map[int]int
	m1 = make(map[int]int, 5)
	m1[1] = 2
	m1[3] = 8
	m1[7] = 0
	m1[6] = 7
	fmt.Println(m1)

	keys := []int{}
	for k,_ := range m1{
		keys = append(keys,k)
	}
	fmt.Println(keys)
	sort.Ints(keys)
	fmt.Println(keys)
	for _,v := range keys{
		fmt.Printf("m1[%d]=%d\n",v,m1[v])
	}
}
